<template>
  <div class="modelreports" ref="modelreports">
      <modelView ref="modelView" v-show="activeView == 1" :modelLists="modelList" @modelLoadFnc="modelLoadFnc" v-if="modelList.length" />
      <ctView ref="ctView" v-show="activeView == 2" :ctLists="ctList"  v-if="ctList.length&&modelLoaded"/>
      <!--<ctView ref="ctView" v-show="activeView == 2" :ctLists="ctList" v-if="ctList.length"/>-->
      <infoView v-model="reportsInfo" :before-close="() => { reportsInfo = false }" :patientInfo="patientInfo"/>
      <markView ref="markView" v-show="activeView == 3"/>
      <div class="img-test" v-show="copperImgShow" style="position:fixed;top:0;width:100%;height:100%;background-color:#dddddd;z-index:999">
        <div style="height:40px;">
          <el-button type="info" plain style="margin: 4px 5px;float:right;" @click="sureSava">确定</el-button>
          <el-button type="info" plain style="margin: 4px 5px;float:right;" @click="cancelCopper">取消</el-button>
        </div>

        <div class="imgContainer" style="height:auto;">
          <img alt="img" style="width:100%;height:auto;" :src="imgUrl" ref="imgTest">
          <!--<img alt="img" style="width:50%;height:auto;" src="@/assets/test.png" ref="imgTest" >-->
        </div>


      </div>

    <div class="floatingTouch">
      <el-button type="text" @click="reportsInfo = !reportsInfo" :class="{active: reportsInfo}">
        <i class="icon-button info-icon"></i>
      </el-button>
      <el-button type="text" @click="activeView = 1" :class="{active: activeView == 1}">
        <i class="icon-button model-icon"></i>
      </el-button>
     <el-button type="text" @click="activeView = 2; $refs.ctView.onWindowResize()" :class="{active: activeView == 2}" v-if="ctList.length">
        <i class="icon-button ct-icon"></i>
      </el-button>
      <!--<el-button type="text" @click="activeView = 2; $router.push({path:'/enquiry/ctView',query:{'list':ctList}})" :class="{active: activeView == 2}" v-if="ctList.length">
        <i class="icon-button ct-icon"></i>
      </el-button>-->
      <el-button type="text" @click="markFn" :class="{active: activeView == 3}">
        <i class="icon-button mark-icon"></i>
      </el-button>
      <el-button type="text" @click="clipPhoto" v-if="activeView !==3">
        <i class="icon-button icon-photo"></i>
      </el-button>
      <el-button type="text" @click="previewFile(graphicReport,urlPrefix)">
        <i class="icon-button report-icon"></i>
      </el-button>
    </div>
  </div>
</template>

<script>
import {previewFile} from '@/utils/tools/tools'
import {queryPatientByMrId} from '@/depends/api/patient'
import {queryMedicalRecordOne, editMedicalRecord, uploadBase64} from '@/depends/api/medicalRecord'



import modelView from './component/modelView'
import ctView from './component/ctView'

import infoView from './component/infoView'
import markView from './component/markView'

import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

let saveLoad = false
let myCropper = null
let afterImg = ''
let c_h = 0

export default {
  components: {
    modelView,
    ctView,
    infoView,
    markView
  },
  data() {
    return {
      pageUrl: this.$route.params,
      activeView: 1,
      reportsInfo: false,
      modelLoaded: false,
      patientInfo: {
        name: '',
        sex: '',
        age: '',
        feature: '',
        ctImgUrl: ''
      },
      modelList: [],
      ctList: [],
      graphicReport:'',
      urlPrefix:'',
      c_h:0,
      imgUrl:'',
      myCropper:null,
      afterImg:'',
      copperImgShow: false
    };
  },
  // provide () {
  //   return {
  //     patientInfo: this.patientInfo
  //   }
  // },
  computed:{
  },
  created() {
    this.queryPatientByMrId()
    this.queryMedicalRecordOne()

  },
  mounted() {
  },
  methods:{
    //模型页加载完成,传递方法值过来
    modelLoadFnc(data){         
      this.modelLoaded = data
    },
    previewFile,
    goCTView(){

    },
    queryPatientByMrId () {
      queryPatientByMrId({mrId: this.pageUrl.id}).then(res => {
        if (res.data.status != 200) {return}
        this.patientInfo.name = res.data.data.name
        this.patientInfo.sex = res.data.data.sex
        this.patientInfo.age = res.data.data.age
      })
    },
    queryMedicalRecordOne () {
      queryMedicalRecordOne({id: this.pageUrl.id}).then(res => {
        if (res.data.status != 200) {return}
        this.patientInfo.feature = res.data.data.medicalRecordDescribe
        if (!res.data.data.screenageModelUrl) { this.modelList = [];  } else {
          this.urlPrefix = res.data.data.urlPrefix;
          this.graphicReport = res.data.data.graphicReport;
          this.modelList = res.data.data.screenageModelUrl.split(',').map((a, b) => {
            const mInfo = a.split(':')
            // id :模型索引
            return {
              id: b,
              color: '#fff',
              opacity: 1,
              name: mInfo[0],
              show: true,
              showInfo: false,
              volume: 0,
              area: 0,
              boxsize: {},
              url: res.data.data.urlPrefix + mInfo[1]
            }
          })
        }

        if (!res.data.data.ctImgUrl) { this.ctList = [];  } else {
          this.ctList = res.data.data.ctImgUrl.split(',').map((a, b) => {
            const mInfo = a.split(':')
            // id :CT索引
            return {
              id: b,
              ctLayerThickness: res.data.data.ctLayerThickness,
              ctMaxZ: res.data.data.ctMaxZ,
              ctPixelSize: res.data.data.ctPixelSize,
              ctMaxX: res.data.data.ctMaxX,
              ctMaxY: res.data.data.ctMaxY,

              name: mInfo[0],
              // url: res.data.data.urlPrefix + mInfo[1]
              url: mInfo[1]
            }
          })
        }
      })
    },
    async clipPhoto () {
      if (saveLoad) { return }
      saveLoad = true
      //let photo = await this.$refs[this.activeView==1?'modelView':'ctView'].clipPic()
      // let photo = await this.$refs['modelView'].clipPic()
      let photo;
      if(this.$refs.ctView){
        photo = await this.$refs[this.activeView==1?'modelView':'ctView'].clipPic()
      }else{
        photo = await this.$refs['modelView'].clipPic()
      }  
      if(this.activeView !==3){
        this.copperImgShow = true;
        this.getCopper(photo);
      }



      // this.$prompt('请输入截图名称', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     center: true
      //   }).then(({ value }) => {
      // 
      // let par = {
      //   id: this.pageUrl.id,
      //   screenshotBase64Name: value || ''
      // }
      // if (this.activeView === 1) {
      //   par.modelScreenshotBase64 = base64
      // } else if (this.activeView === 2) {
      //   par.ctScreenshotBase64 = base64
      // }
      // uploadBase64(par).then(res => {
      //   if (res.data.status == 200) {
      //     this.$message.success('保存成功!')
      //   } else {
      //     this.$message.error('添加成功!')
      //   }
      // })

      //   })
    },
    saveHtmlPic (base64, viewType) {
      // console.log('save', base64)
      this.$prompt('请输入截图名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }).then(({ value }) => {
          let par = {
            id: this.pageUrl.id,
            screenshotBase64Name: value || ''
          }
          if (viewType === 1) {
            par.modelScreenshotBase64 = base64
          } else if (viewType === 2) {
            par.ctScreenshotBase64 = base64
          }
          
          uploadBase64(par).then(res => {
            if (res.data.status == 200) {
              this.$message.success('保存成功!')
            } else if (res.data.status == -1) {
              this.$message.error('该账户不能保存截图!')
            } else {
              this.$message.error('添加成功!')
            }
            this.myCropper.destroy();
            this.copperImgShow = false;
          })
        }).catch(() => {
        this.copperImgShow = false;
        this.myCropper.destroy();
          // 
        })
    },
    async markFn () {
      // c_h = this.$refs.ctView.$refs.screen3d.clientHeight || this.$refs.modelView.$refs.screen3d.clientHeight ;
      // c_h = this.$refs.modelView.$refs.screen3d.clientHeight ;
      if(this.$refs.ctView){
        this.c_h = this.$refs.ctView.$refs.screen3d.clientHeight
      }else{
        this.c_h = this.$refs.modelView.$refs.screen3d.clientHeight
      }
      if (this.activeView == 3) { return }
      let dataURL = ''
      let prevActiveView = this.activeView
      if (this.activeView == 1) {
        dataURL = await this.$refs.modelView.clipPic()
      } else if (this.activeView == 2) {
        dataURL = await this.$refs.ctView.clipPic()
      }
      this.activeView = 3
      this.$nextTick(() => {
        // let h = this.$refs.ctView.$refs.screen3d.clientHeight;
        this.$refs.markView.showImg(dataURL, prevActiveView, this.c_h)
      })

      // let dataURL = await this.clipPic()
      // this.handleBottomBtn.mark = true
      // this.$nextTick(() => {
      //   this.$refs.vMark.showImg(dataURL)
      // })
      
      // ----------------------------------------------------------------------------
      // // 隐藏完成
      // console.log(this.commentBox.comments)
      // console.log(this.handleBottomBtn.measureLongArr)
      // console.log(this.handleBottomBtn.measureAngleArr)
      // // 清除未完成
      // this.clearUnfinished()


      // console.log(this.$refs.screen3d.querySelector('canvas').toDataURL())
    },
    async getImage (imgSrc, space = 255) {
      return new Promise(resolve => {

        let img = new Image()
        img.src = imgSrc
        img.onload = () => {
          let canvas1 = document.createElement("canvas")
          let ctx1 = canvas1.getContext('2d')
          let canvas2 = document.createElement("canvas")
          let ctx2 = canvas2.getContext('2d')
          canvas1.width = img.width
          canvas1.height = img.height
          ctx1.drawImage(img, 0, 0)

          let imgData = ctx1.getImageData(0, 0, img.width, img.height).data
          let [lOffset, rOffset, tOffset, bOffset] = [img.width, 0, img.height, 0]
          for (let i = 0; i <= img.width; i++) {
              for (let j = 0; j <= img.height; j++) {
                  let pos = (i + img.width * j) * 4
                  if (imgData[pos] == space || imgData[pos + 1] == space || imgData[pos + 2] == space || imgData[pos + 3] == space) {
                      bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
                      rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
                      tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
                      lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
                  }
              }
          }
          lOffset++
          rOffset++
          tOffset++
          bOffset++

          canvas2.width = rOffset - lOffset
          canvas2.height = bOffset - tOffset
          ctx2.drawImage(img, lOffset, tOffset, canvas2.width, canvas2.height, 0, 0, canvas2.width, canvas2.height)
          resolve(canvas2.toDataURL())
        }
      })
    },
    init(){
      this.myCropper = new Cropper(this.$refs.imgTest, {
        viewMode: 1,
        dragMode: 'none',
        /*initialAspectRatio: 1,*/
        guides:true,
       /* aspectRatio: 1,*/
        preview: '.before',
        background: false,
        /*autoCropArea: 1,*/
        fixedBox:false,
        centerBox:false,
        autoCropArea: 0.8,
        zoomOnWheel: false
      })
    },
    getCopper(photo){
      this.imgUrl = photo;
      this.$nextTick(()=>{
        this.init();
      });
    },
    sureSava(){
      this.afterImg = this.myCropper.getCroppedCanvas({
        imageSmoothingQuality: 'high'
      }).toDataURL('image/png')
      if(this.afterImg !==''){
        this.saveHtmlPic(this.afterImg, this.activeView)
        saveLoad = false

      }
    },
    cancelCopper(){
      this.copperImgShow=false;
      saveLoad = false;
      if(this.myCropper){
        this.myCropper.destroy();
      }

    }
  },
}
</script>
<style scoped lang="less">

.modelreports {
  height: 100%;
  overflow: hidden;
  position: relative;
  .floatingTouch {
    position: absolute;
    top: 100px;
    right: 10px;
    z-index: 2;
    .el-button {
      display: block;
      padding: 0 !important;
      margin: 0;
      border: none;
      margin-bottom: 6px;
      &.active {
        background-color: #f6f6f6;
      }
    }
    .icon-button {
      width: 36px;
      height: 36px;
      display: block;
      background-size: 32px 32px;
      background-repeat: no-repeat;
      background-position: center;
      &.info-icon {
        background-image: url(/static/images/info-icon.png);
      }
      &.model-icon {
        background-image: url(/static/images/model-icon.png);
      }
      &.ct-icon {
        background-image: url(/static/images/ct-icon.png);
      }
      &.mark-icon {
        background-image: url(/static/images/mark-icon.png);
      }
      &.icon-photo {
        background-image: url(/static/images/icon-photo.png);
      }
      &.report-icon {
        background-image: url(/static/images/report-icon.png);
      }
    }
  }
}
</style>

<style lang="less">
@nav_height: 30px;
.omit {
  white-space: nowrap;
  overflow:  hidden;
  text-overflow:  ellipsis;
}
.modelreports {
  .v-header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    height: @nav_height;
    // background-color: #3F3F3F;
    background-color: #1296DB;
    color: #fff;
    text-align: center;
    z-index: 2;
    .header {
      position: relative;
      .infoBox {
        padding: 2px @nav_height;
        .name {
          font-size: 16px;
          height: 30px;
          line-height: 30px;
          .omit();
        }
        .logoImg {
          height: 26px;
          img {
            max-height: 100%;
          }
        }
        .feature {
          color: #333;
          position: absolute;
          left: 10px;
          right: 10px;
          top: @nav_height + 10;
          font-size: 12px;
          // height: 12px;
          // line-height: 12px;
          text-align: left;
        }
      }
      .l,.r {
        position: absolute;
        width: @nav_height;
        height: @nav_height;
        line-height: @nav_height;
        top: 0;
        cursor: pointer;
      }
      .l {
        left: 0;
        .amsp {
          font-size: 14px;
        }
      }
      .r {
        right: 0;
        .amsp {
          font-size: 14px;
        }
      }
    }
  }
  .v-bottom {
    position: fixed;
    height: @nav_height;
    bottom: 0;
    left: 0;
    width: 100%;
    padding:0 20px;
    display: flex;
    // background-color: #F4F4F4;
    // opacity: 0.5;
    background-color: rgba(244,244,244, 0.5);
    overflow-y: hidden;
    overflow-x: auto;
    align-items: center;
    z-index: 2;
    .vb-item {
      flex: 1;
      color: #515151;
      padding: 0px 10px;
      text-align: center;
      position: relative;
      &.active {
        color: #1296DB;
      }
      .amsp {
        margin-top: 2px;
        height: 14px;
        font-size: 14px;
      }
      .vb-name {
        margin-top: 2px;
        display: block;
        font-size: 10px;
        height: 10px;
        line-height: 10px;
        white-space: nowrap;
      }
    }
  }
  .v-bottom-two {
    position: fixed;
    bottom: @nav_height;
    left: 0;
    width: 100%;
    background-color: rgba(240,240,240, 0.4);
    // padding: 0px 15px;
    z-index: 3;
    border-bottom: 1px solid #eee;
    padding: 3px 15px;
    .sectionBtnsBox {
      display: flex;
      .itemBtn {
        width: 12.5%;
        text-align: center;
        color: #515151;
        display: flex;
        flex-direction: column;
        justify-content: center;
        &.active {
          color: #1296DB;
        }
        .amsp {
          height: 14px;
          font-size: 14px;
        }
        .vbt-name {
          display: block;
          font-size: 10px;
        }
      }
    }
    .iptBox {
      display: flex;
      align-items: center;
      .name {
        color: #666;
        width: 70px;
        font-size: 12px;
      }
      .colorBox {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        .clr {
          width: 10%;
          height: 30px;
          margin-right: 1%;
          margin-bottom: 1%;
        }
      }
      .ipt {
        flex: 1;
        .el-slider {
          margin-left: 8px;
        }
      }
      .btns {
        // width: 50px;
        padding-left: 10px;
        text-align: right;
        .amsp {
          font-size: 18px;
          padding: 0 3px;
          &.act {
            color: #1296DB;
          }
        }
      }
    }
  }
  .selectEldrawer {
    .el-drawer__header {
      margin-bottom: 0;
      padding: 10px 20px;
      .el-drawer__close-btn {
        height: 25px;
        line-height: 25px;
      }
    }
    .el-drawer__body {
      ul {
        list-style: none;
      }
      ul.ful {
        display: flex;
        li {
          width: 20%;
        }
      }

    }
  }
}
</style>